<script setup>
import {ref, onBeforeMount} from 'vue'
import Msg from '@/components/message'
import axios from 'axios'
import { uploadApi, removeApi } from '@/commons/api'
import { CScrollbar } from 'c-scrollbar'

// 定义父组件传来的参数
const props = defineProps({
  // 上传种类，1单图，2单文件，3多图片及文件
  kind: {
    type: Number,
    required: true,
    default: 1
  },
  // 多个上传表单的区分
  types: {
    type: Number,
    default: 1
  },
  file: {
    type: Object,
    required: false,
    default: {id: '', name: '', url: ''}
  },
  files: {
    type: Array,
    required: false,
    default: []
  }
})

const fileObj = {id: '', name: '', url: '', thumb: ''}
const fileRef = ref(fileObj)
const fileList = ref([])
const imgArr = ref([])
const fileArr = ref([])
const uped = ref(true)

onBeforeMount(() => {
  fileRef.value = props.file && props.file.name && props.file.name!=='' ? props.file : fileObj
  uped.value = !(fileRef.value && fileRef.value.id && fileRef.value.name !== '')
  fileList.value = props.files && props.files.length>0 ? props.files : []
  fileList.value.forEach(file => {
    const extName = file.url.substring(file.url.lastIndexOf('.'), file.url.length)
    if('.jpg.png.bmp.gif'.indexOf(extName) !== -1) {
      imgArr.value.push(file)
    } else {
      fileArr.value.push(file)
    }
  })
})


// 定义子组件调用父组件的方法
const emits = defineEmits(['setUrl'])

// 上传表单
const fileForm = ref('fileForm')

// upload 上传文件
const upload = async (event) => {
  if(event) {
    let file = event.target.files[0]
    let allowed = props.kind===1 ? 'image/jpeg|image/png|image/bmp|image/gif' : 'image/jpeg|image/png|image/bmp|image/gif|video/mp4|text/plain|text/css|text/csv|application/vnd.ms-works|application/msword|application/pdf|application/vnd.ms-powerpoint|application/vnd.ms-excel|zip/mp4|media/mp4|aplication/zip|application/vnd.openxmlformats-officedocument.spreadsheetml.sheet|application/vnd.openxmlformats-officedocument.wordprocessingml.document|application/vnd.openxmlformats-officedocument.presentationml.presentation'
    if(!file || allowed.indexOf(file.type) === -1) {
      Msg({kind: 'warn', txt: '对不起，平台不允许上传该格式的文件，请改换！'})
      return
    } else {
      let formData = new FormData()
      // Form表单对应的File表单
      formData.append('upFile', file)
      const res = await uploadApi(formData)
      if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
        if(props.kind===1 || props.kind===2) {
          // 单文件
          uped.value = false
          fileRef.value = res.data
          emits("setUrl", props.kind, props.types, fileRef.value)
        } else {
          // 多文件
          fileList.value.push(res.data)
          const curFile = res.data
          const extName = curFile.url.substring(curFile.url.lastIndexOf('.'), curFile.url.length)
          if('.jpg.png.bmp.gif'.indexOf(extName) !== -1) {
            imgArr.value.push(curFile)
          } else {
            fileArr.value.push(curFile)
          }
          emits('setUrl', props.kind, props.types, fileList.value)
        }
        Msg({kind: 'success', txt: '文件上传成功！'})
      } else {
        Msg({kind: 'error', txt: res.msg})
      }
    }
  }
  fileForm.value.value = ''
}

// download 下载文件
const download = async (url) => {
  // axios.post('http://127.0.0.1:8010/common/download', {url}, { responseType: 'blob' }).then(res => {
  axios.post('http://sc-api.haobing.pw/common/download', {url}, { responseType: 'blob' }).then(res => {
      let aTag = document.createElement('a')
    aTag.href = window.URL.createObjectURL(new Blob([res.data]))
    aTag.download = decodeURI(res.headers['content-disposition'].split('=')[1].replace(' ', ''))
    aTag.click()
    window.URL.revokeObjectURL(aTag.href)
  }).catch(function (err) {
    Msg({kind: 'error', txt: err})
  })
}

// remove 删除当前文件
const remove = async (file) => {
  if(!file && !file.url || file.url==='') {
    Msg({ kind: 'warn', txt: '请求的参数不能为空！' })
    return
  }
  const res = await removeApi({ url: file.url })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    if(props.kind===1 || props.kind===2) {
      uped.value = true
      fileRef.value = fileObj
      emits("setUrl", props.kind, props.types, fileRef.value)
    } else {
      imgArr.value.splice(imgArr.value.findIndex(cur => cur.id === file.id), 1)
      fileArr.value.splice(fileArr.value.findIndex(cur => cur.id === file.id), 1)
      fileList.value.splice(fileList.value.findIndex(cur => cur.id === file.id), 1)
      emits('setUrl', props.kind, props.types, fileList.value)
    }
    Msg({ kind: 'success', txt: '恭喜您，文件删除成功！' })
  } else {
    Msg({ kind: 'error', txt: res.msg })
  }
}

// view 预览图片
const showed = ref(false)
const imgRef = ref({name: '', url: ''})
const view = (name, url) => {
  showed.value = true
  imgRef.value.name = name
  imgRef.value.url = url
}

// close 关闭预览框
const close = (kind) => {
  if(kind === 1) {
    showed.value = false
  } else {
    showed.value = false
    imgRef.value = {name: '', url: ''}
  }
}
</script>

<template>
  <div class="up-a">
    <div class="up-b" v-if="props.kind===1">
      <div class="up-c" v-if="uped"><i class="iconfont fs30">&#xea80;</i><input type="file" ref="fileForm" class="up-p" @change="upload($event)" /></div>
      <div v-else>
        <div class="up-d"><img :alt="fileRef.name" v-lazy="fileRef.thumb" class="up-e" /></div>
        <div class="up-f">
          <div class="up-g" @click="view(fileRef.name, fileRef.url)"><i class="iconfont fs20">&#xea8d;</i></div>
          <div class="up-g" @click="remove(fileRef)"><i class="iconfont fs20">&#xea45;</i></div>
        </div>
      </div>
    </div>
    <div v-if="props.kind===2">
      <div class="up-h" v-if="uped"><i class="iconfont">&#xea80;</i> 上传文件<input type="file" ref="fileForm" class="up-p" @change="upload($event)" /></div>
      <div class="up-i" v-else>
        <div class="up-j"><i class="iconfont">&#xea32;</i> {{fileRef.name}}</div>
        <div class="up-k" @click="download(fileRef.url)"><i class="iconfont">&#xeaa2;</i> 下载</div>
        <div class="up-l" @click="remove(fileRef)"><i class="iconfont">&#xea45;</i> 删除</div>
      </div>
    </div>
    <div v-if="props.kind===3">
      <div class="up-h"><i class="iconfont">&#xea80;</i> 新增文件<input type="file" ref="fileForm" class="up-p" @change="upload($event)" /></div>
      <div class="up-b">
        <div v-for="cur in imgArr" :key="cur.id" style="margin: 0 15px 15px 0;">
          <transition name="fade-mod" appear>
            <div class="up-d"><img :alt="cur.name" v-lazy="cur.thumb" class="up-e" /></div>
          </transition>
          <div class="up-f">
            <div class="up-g" @click="view(cur.name, cur.url)"><i class="iconfont fs20">&#xea8d;</i></div>
            <div class="up-g" @click="remove(cur)"><i class="iconfont fs20">&#xea45;</i></div>
          </div>
        </div>
      </div>
      <div>
        <div class="up-i" v-for="cur in fileArr" :key="cur.id">
          <div class="up-j"><i class="iconfont">&#xea32;</i> {{cur.name}}</div>
          <div class="up-k" @click="download(cur.url)"><i class="iconfont">&#xeaa2;</i> 下载</div>
          <div class="up-l" @click="remove(cur)"><i class="iconfont">&#xea45;</i> 删除</div>
        </div>
      </div>
    </div>
    <transition name="fade-mod" appear>
      <div v-show="showed" class="modal-backdrop">
        <c-scrollbar>
          <div v-if="showed" class="modal" style="width: 1100px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 图片详情</div>
              <div class="header-right" @click="close(2)"><i class="iconfont fs20">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div class="up-m"><img :alt="imgRef.name" v-lazy="imgRef.url" class="up-n" /></div>
            </div>
            <div class="modal-footer">
              <div class="btn-d up-o" @click="close(2)"><i class="iconfont">&#xea4f;</i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
  </div>
</template>

<style scoped>
.up-a {width: 100%;}
.up-b {display: inline-flex; display: -webkit-inline-flex; flex-wrap: wrap;}
.up-c {padding: 30px; margin: 0 15px 15px 0; position: relative; color:#409EFF; background-color: #FFF; border: 1px dashed #4099FF; border-radius: 4px; cursor: pointer;}
.up-c:hover {border: 1px solid #66B1FF;}
.up-d {width: 90px; height: 90px; overflow: hidden; border: 1px solid #4099FF; border-radius: 4px; text-align: center;}
.up-e {height: 100%;}
.up-f {width: 91px; height: 91px; border-radius: 4px; margin-top: -91px; position: relative; opacity: 0; cursor: pointer;}
.up-f:hover {opacity: 1; background-color: rgba(0, 0, 0, .5);}
.up-g {padding-top: 15px; text-align: center; color: #FFF;}

.up-h {width: 85px; height: 20px; padding: 5px 10px; margin-bottom: 15px; position: relative; color:#FFF; background-color: #409EFF; border-radius: 4px; cursor: pointer;}
.up-h:hover {background-color: #66B1FF;}
.up-i {width: calc(100% - 40px); line-height: 30px; padding: 10px 20px; border-bottom: 1px dashed #E0E0E0; display: flex; display: -webkit-flex;}
.up-j {flex-grow: 1;}
.up-k {width: 100px; text-align: right; cursor: pointer; color: #4099FF;}
.up-l {width: 100px; text-align: right; cursor: pointer; color: #d03050;}

.up-m {text-align: center;}
.up-n {max-width: 100%;}
.up-o {margin: 10px 15px; cursor: pointer;}
.up-p {position: absolute; opacity: 0; width: 92px; height: 32px; margin-left: -84px; cursor: pointer;}
</style>
